using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System;
using System.Threading;
using Reply.Seat.LeadCollector.BL;
using Reply.Seat.LeadCollector.UI;
namespace Reply.Seat.LeadCollector.iPhone
{
	// The name AppDelegate is referenced in the MainWindow.xib file.
	public partial class AppDelegate : UIApplicationDelegate
	{
		// This method is invoked when the application has loaded its UI and its ready to run
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			// If you have defined a view, add it here:
			window.AddSubview (tabBarController.View);
			window.MakeKeyAndVisible ();
			
			sincronizzaBtn.Clicked += HandleSincronizzaBtnClicked;
			Thread.Sleep(1000);
			return true;
		}

		void HandleSincronizzaBtnClicked (object sender, EventArgs e)
		{
			using (WaitAnimation wa = new WaitAnimation (null)) {
				///Aggiorna la UI mettendo in attesa
				wa.StartWait ();
				new Thread (() =>
				{
					foreach (var lead in SharedObjects.LeadNonSincronizzati.ToArray ()) {
						if (SharedObjects.Logic.TrySyncronizeLead (lead)) {
							SharedObjects.LeadNonSincronizzati.Remove (lead);
							SharedObjects.LeadSincronizzati.Add (lead);
							BeginInvokeOnMainThread (() =>
							{
								nonSincronizzatiTvc.TableView.ReloadData ();
								UpdateNonSincronizzatiBadge ();
							});
						}
					}
					BeginInvokeOnMainThread (() => { wa.EndWait (); });
				}).Start ();
			}
		}

		public void UpdateNonSincronizzatiBadge ()
		{
			if (SharedObjects.LeadNonSincronizzati.Count > 0)
				nonSincronizzatiTbi.BadgeValue = SharedObjects.LeadNonSincronizzati.Count.ToString ();
			else
				nonSincronizzatiTbi.BadgeValue = null;
		}


		// This method is required in iPhoneOS 3.0
		public override void OnActivated (UIApplication application)
		{
		}
	}
}
